package com.standardoperationapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.device.DeviceManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.rfid.trans.ReaderHelp;
import com.rfid.trans.ReaderParameter;
import com.standardoperationapp.R;
import com.standardoperationapp.adapter.RFIDWriteAdapter;
import com.standardoperationapp.bean.RfidCodeListBean;
import com.standardoperationapp.databinding.ActivityRfidwriteBinding;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.net.MaterialApi;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.utils.OtgUtils;
import com.standardoperationapp.utils.Reader;
import com.standardoperationapp.utils.StringUtil;
import com.standardoperationapp.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RFID卡读写
 */
public class RFIDWriteActivity extends AppCompatActivity {

    /**
     * 串口名字
     */
    public static final String comPort = "/dev/ttyHSL0";
    /**
     * 波特率
     */
    public static final int baudRate = 115200;
    public static final int baudRate2 = 57600;
    private static final String TAG = "lpc";

    ActivityRfidwriteBinding binding;

    RFIDWriteAdapter adapter;

//    public static ReaderHelp rrlib;
    /**
     * 初始密码
     */
    private static final String rfidPassword = "00000000";;
    private List<RfidCodeListBean.DataDTO> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_rfidwrite);

        dataList = new ArrayList<>();
        adapter = new RFIDWriteAdapter(RFIDWriteActivity.this, dataList);
        binding.listView.setAdapter(adapter);
        binding.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 写入射频卡
                writeRFIDCard(dataList.get(i).getMaterRfid());
            }
        });

        initData();
        initSound();

        binding.read.setOnClickListener(view -> {
           readTag();
        });
        binding.write.setOnClickListener(view -> {
            String rfidCode = binding.etInfo.getText().toString();
            writeRFIDCard(rfidCode);
        });
    }

    /**
     * 写卡
     * @param rfidCode
     */
    private void writeRFIDCard(String rfidCode) {
        if (rfidCode.isEmpty()) {
            return;
        }
//        rfidCode = "sf123456";
        String hex = StringUtil.stringToHex(rfidCode);
        Log.d(TAG, "onCreate: 转换后的16进制数据=" + hex);
        // Mem 待写入的存储区，1-EPC区
        int result = Reader.rrlib.WriteData_G2(hex,"", (byte) 1, 02, rfidPassword);
        if(result!=0){
            Log.d(TAG, "onCreate: 写入失败");
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("写入失败!")
                    .setPositiveButton("确定", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    }).show();
        } else{
            Log.d(TAG, "onCreate: 写入成功");
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("写入成功!")
                    .setPositiveButton("确定", (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    }).show();

            submitInfo(rfidCode,"1");
        }
    }

    private void readTag() {
        String s = Reader.rrlib.ReadData_G2("", (byte) 1, 02, (byte) 8, rfidPassword);
        if (s == null) {
            ToastUtil.showToast("读卡失败");
        } else {
            Log.d(TAG, "读卡的数据: " + s);
            String value = StringUtil.hexToString(s);
            Log.d(TAG, "转换后的数据: " + value);
            ToastUtil.showToast("读卡成功：" +value);
        }
    }
    private void initData() {
        MaterialApi.getAppRfidCodeList(new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                dataList.clear();
                RfidCodeListBean bean = GsonUtils.fromJson(result.toString(), RfidCodeListBean.class);
                if (bean.getData() != null) {
                    dataList.addAll(bean.getData());
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        }));
    }

    /**
     *  是否开启 手柄按钮 扫码二维码 （扫描头出光）
     *  在自己的业务逻辑需要关闭或打开之前，调用该方法（注意：不能在按下手柄按钮后调用，因为按钮按下后就会触发出光扫码）。
     * @param isopen     true:开启   false:关闭
     */
    private void setOpenScan523(boolean isopen) {
        try{
            DeviceManager mDeviceManager = new DeviceManager();
            if (mDeviceManager != null) {
                if (isopen) {
                    //TODO 设置触发 523键值(手柄按钮) 扫描出光
                    mDeviceManager.setSettingProperty("persist-persist.sys.rfid.key", "0-");
                    mDeviceManager.setSettingProperty("persist-persist.sys.scan.key", "520-521-522-523-");//这里入参传入了哪些键值，在按下键值的的时候就会调起扫描头出光
                }else {
                    //TODO 设置触发 523键值(手柄按钮) 不扫描出光
                    mDeviceManager.setSettingProperty("persist-persist.sys.rfid.key", "0-");
                    mDeviceManager.setSettingProperty("persist-persist.sys.scan.key", "520-521-522-");//这里入参传入了哪些键值，在按下键值的的时候就会调起扫描头出光
                }
            }
        }catch(Exception ex)
        {}
    }
    @Override
    protected void onResume() {
//        Reader.rrlib.PowerControll(null, true);
        setOpenScan523(false);
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        setOpenScan523(true);
    }

    public boolean keyPress =false;
    /**
     *按键扫描RFID
     **/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==523 && !keyPress)
        {
            keyPress = true;
            readTag();
        }
        else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     *按键扫描RFID
     **/
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode==523)
        {
            keyPress =false;
        }
        return super.onKeyUp(keyCode, event);
    }


    private void submitInfo(String rfidCode, String rfidStatus) {
        MaterialApi.updateAppRfidCodeStatus(rfidCode,rfidStatus,new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        }));
    }

    static HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    private static SoundPool soundPool;
    private static float volumnRatio;
    private static AudioManager am;
    private  void initSound(){
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundMap.put(1, soundPool.load(this, R.raw.barcodebeep, 1));
        am = (AudioManager) this.getSystemService(AUDIO_SERVICE);// 实例化AudioManager对象
        Reader.rrlib.SetSoundID(soundMap.get(1),soundPool);
    }


    @Override
    protected void onDestroy() {
//        Reader.rrlib.PowerControll(null, false);
//        Reader.rrlib.DisConnect();
        super.onDestroy();
    }
}